package com.ml.view;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.ml.app.MyApplication;
import com.ml.tools.BaseActivity;
import com.ml.tools.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MyPaizhao extends BaseActivity {

    View view;
    RequestQueue mQueue = null;
    JsonObjectRequest mJsonObjectRequest = null;
    boolean b = true;
    boolean bb = false;//是否可以开始加载图片
    AssetFileDescriptor afd = null;
    AssetManager am = null;
    private final TextView[] tx = new TextView[6];
    private ImageView image;
    private String url2 = MyApplication.SERVERPATH + "/Y502/GetZhenKanbanData";//sn riqi
    private String logourl = MyApplication.SERVERPATH + "/Y502/loadZhenChenImg";//sn
    private String url3 = MyApplication.SERVERPATH + "/Y502/GetBadlynetitywz";  //riqi sn;
    private String riqi, taitou, uu, yichangstr, name;
    private final List<String> li = new ArrayList<String>();//存储抽检不良信息
    private TextView ttitle;
    private TextView ttishi;
    private TextView ttime;
    private final MediaPlayer mediaPlayer = new MediaPlayer();
    Handler mHander = new Handler() {
        public void handleMessage(Message msg) {
            try {
                switch (msg.what) {
                    case 1: {
                        JSONObject json = (JSONObject) msg.obj;
                        String re1 = json.toString();
                        String re = json.getString("result");
                        if (re.equals("yes")) {
                            JSONArray array = json.optJSONArray("data");
                            ttishi.setText("");
                            if (array != null) {
                                li.clear();
                                int n = array.length();
                                if (n > 6)
                                    n = 6;
                                for (int i = 0; i < n; i++) {
                                    JSONObject obj = array.optJSONObject(i);
                                    if (MyApplication.yy.equals("zh"))
                                        name = obj.getString("name");
                                    else if (MyApplication.yy.equals("en"))
                                        name = obj.getString("nameen");
                                    else
                                        name = obj.getString("namevi");
                                    li.add(name + ":" + obj.optInt("num"));
                                }
                            }
                            setData();
                            if (!re1.equals(MyApplication.urls)) {
                                MyApplication.urls = re1;
                                bb = true;
                            }
                        }
                    }
                    break;
                    case 2: {
                        setImage();
                    }
                    break;
                    case 3: {
                        JSONObject json = (JSONObject) msg.obj;
                        String re = json.getString("result");
                        int nn = 0, nnn = 0;
                        boolean t = false;
                        if (re.equals("yes")) {
                            JSONArray array = json.optJSONArray("data");
                            ttishi.setText("");
                            if (array != null) {
                                int n = array.length();
                                if (MyApplication.lli.size() == 0) {
                                    for (int i = 0; i < n; i++) {
                                        JSONObject obj = array.optJSONObject(i);
                                        nn = obj.optInt("num");
                                        MyApplication.lli.add((nn / 5) * 5);
                                    }
                                } else {
                                    for (int i = 0; i < n; i++) {
                                        JSONObject obj = array.optJSONObject(i);
                                        String name = obj.optString("name");
                                        nn = obj.optInt("num");//最新不良代码数 12
                                        nnn = MyApplication.lli.get(i);//历史不良代码数，5的倍数  5
                                        if (nn - nnn >= 5) {
                                            int n1 = nn / 5;
                                            MyApplication.lli.set(i, n1 * 5);
                                            if (MyApplication.yy.equals("zh"))
                                                MyApplication.name2 = obj.getString("name");
                                            else if (MyApplication.yy.equals("en"))
                                                MyApplication.name2 = obj.getString("nameen");
                                            else
                                                MyApplication.name2 = obj.getString("namevi");
                                            MyApplication.name = name;
                                            startActivity(new Intent(MyPaizhao.this, MyChapo.class));
                                            initMediaPlayer();
                                            break;
                                        }
                                    }
                                }

                            }
                        }
                    }
                    break;
                }
            } catch (Exception ex) {
                ttishi.setText(yichangstr);
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_main3);
        taitou = getIntent().getStringExtra("taitou");
        riqi = getIntent().getStringExtra("riqi");
        url2 = url2 + "?sn=" + MyApplication.sn + "&&riqi=" + riqi;
        url3 = url3 + "?sn=" + MyApplication.sn + "&&riqi=" + riqi;
        logourl = logourl + "?sn=" + MyApplication.sn;
        yichangstr = MyApplication.map.get("yichang");
        am = getAssets();
        try {
            afd = am.openFd("track26.mp3");
        } catch (IOException e) {
            Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show();
        }
        setView();
        mQueue = MyApplication.getRequestQueue();
        new MyThread().start();
    }

    @Override
    protected void onDestroy() {
        b = false;
        super.onDestroy();
    }

    private void setView() {
        tx[0] = (TextView) findViewById(R.id.main3_bh1);
        tx[1] = (TextView) findViewById(R.id.main3_bh2);
        tx[2] = (TextView) findViewById(R.id.main3_bh3);
        tx[3] = (TextView) findViewById(R.id.main3_bh4);
        tx[4] = (TextView) findViewById(R.id.main3_bh5);
        tx[5] = (TextView) findViewById(R.id.main3_bh6);
        image = (ImageView) findViewById(R.id.main3_image);
        if (MyApplication.bit != null)
            setImage();
        ttime = (TextView) findViewById(R.id.main3_time);
        ttitle = (TextView) findViewById(R.id.main3_title);
        ttitle.setText(taitou);
        ttishi = (TextView) findViewById(R.id.main3_tishi);
    }

    public void setData() {
        for (int i = 0; i < li.size(); i++) {
            tx[i].setText(li.get(i));
        }
    }

    public void setImage() {
        image.setImageBitmap(MyApplication.bit);
    }

    private void getData() {
        boolean isConnected = Utils.toastIsNetworkConnected(this);
        if (isConnected) {

            mJsonObjectRequest = new JsonObjectRequest(Request.Method.POST, uu,
                    null, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    parseData(response);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
//					Toast.makeText(MyPaizhao.this,MyApplication.map.get("network_error_try_again"), Toast.LENGTH_LONG).show();
                }
            }
            );
            mQueue.add(mJsonObjectRequest);
        } else {
//				Toast.makeText(MyPaizhao.this,MyApplication.map.get("network_error_try_again"), Toast.LENGTH_LONG).show();
            return;
        }
    }

    protected void parseData(JSONObject response) {
        Message msg = mHander.obtainMessage();
        if (uu.equals(url2))
            msg.what = 1;
        else if (uu.equals(url3))
            msg.what = 3;
        msg.obj = response;
        mHander.sendMessage(msg);
    }

    private void getLogo() {
        ImageRequest imageRequest = new ImageRequest(
                uu,
                new Response.Listener<Bitmap>() {
                    @Override
                    public void onResponse(final Bitmap response) {
                        Message msg = mHander.obtainMessage();
                        msg.what = 2;
                        if (MyApplication.bit != null) {
                            MyApplication.bit.recycle();
                            MyApplication.bit = null;
                            System.gc();
                        }
                        MyApplication.bit = zoomBitmap(response);
                        mHander.sendMessage(msg);
                    }
                }, 0, 0, Config.RGB_565, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Message msg = mHander.obtainMessage();
                msg.what = 2;
                if (MyApplication.bit != null) {
                    MyApplication.bit.recycle();
                    MyApplication.bit = null;
                    System.gc();
                }
                MyApplication.bit = BitmapFactory.decodeResource(getResources(), R.drawable.default_1920_english);
                mHander.sendMessage(msg);
            }
        });
        mQueue.add(imageRequest);
    }

    Bitmap zoomBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        if (width < 2000) {
            return bitmap;
        }

        Matrix matrix = new Matrix();
        int scale = width / 2000; //2000的整数倍
        if (scale < 2) {
            scale = 2;
        }

        float scaleW = 1 / (float) scale;
        matrix.postScale(scaleW, scaleW);
        Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
                matrix, true);
        return newbmp;
    }

    private void initMediaPlayer() {
        try {
            mediaPlayer.reset();
            mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
            mediaPlayer.prepare();
            mediaPlayer.start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class MyThread extends Thread {
        int i = 0;

        @Override
        public void run() {
            uu = url2;
            getData();
            while (b) {
                try {
                    Thread.sleep(1000);
                    if (bb) {
                        uu = logourl;
                        getLogo();
                        bb = false;
                    }
                    i++;
                    if (i == 20) {
                        uu = url3;
                        getData();
                    } else if (i > 30) {
                        MyPaizhao.this.finish();
                        b = false;
                    }

                } catch (InterruptedException e) {

                }
            }
        }
    }
}
